package com.dubbo.boot.consumer;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.dubbo.boot.api.DemoService;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import java.util.Collections;

/**
 * @Descrtption DubboBootConsumer
 * @Author luke
 * @Date 2020/4/9
 **/
@SpringBootApplication
public class DubboBootConsumer {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Reference(version = "1.0.0")
    private DemoService demoService;

    public static void main(String[] args) {
        initFlowRule();
        SpringApplication.run(DubboBootConsumer.class,args);
    }

    @Bean
    public ApplicationRunner runner(){
        //return args -> logger.info(demoService.sayHello("luke"));
        for(int i = 0; i < 10; i++) {
            demoService.sayHello("luke"+i);
        }
        return args -> {};
    }

    /**
     * 流控规则
     */
    private static void initFlowRule(){
        FlowRule flowRule = new FlowRule();
        flowRule.setResource("com.dubbo.boot.api.DemoService:sayHello(java.lang.String)");//资源
        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);//阀值类型
        flowRule.setCount(2);//阀值
        flowRule.setLimitApp("default");
        flowRule.setClusterMode(false);
        flowRule.setStrategy(RuleConstant.STRATEGY_DIRECT);//流控模式
        flowRule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);//流控效果
        FlowRuleManager.loadRules(Collections.singletonList(flowRule));
    }

}
